package pri.black.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.AuthorizationFilter;
import pri.black.dogview.component.CacheService;
import pri.black.dogview.handler.AuthAccessDeniedHandler;
import pri.black.dogview.service.IAdminService;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    IAdminService adminService;

    @Autowired
    CacheService cacheService;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize ->
                        authorize
                                .requestMatchers(HttpMethod.GET, "/").permitAll()
                                .requestMatchers(HttpMethod.GET, "/media/**").permitAll()
                                .requestMatchers(HttpMethod.POST, "/login").permitAll()
                                .requestMatchers(HttpMethod.GET, "/rand").permitAll()
                                .requestMatchers("/loginView").permitAll()
                                .requestMatchers("/blog/**").permitAll()
                                .requestMatchers("/open-source/**").permitAll()
                                .requestMatchers("/dogs-location", "/dogs-status").hasAnyRole("admin")
                                .anyRequest().authenticated()
                )

//                .addFilterBefore(new UsernamePasswordAuthenticationFilter(), AuthorizationFilter.class)
                .addFilterBefore(new AuthFilter(adminService,cacheService), AuthorizationFilter.class)
                .formLogin(AbstractHttpConfigurer::disable)
                .logout(AbstractHttpConfigurer::disable)
                .exceptionHandling(e -> {
                    e.accessDeniedHandler(new AuthAccessDeniedHandler());
                })
                .csrf(AbstractHttpConfigurer::disable);

        return http.build();
    }


//    @Bean
//    public UserDetailsService userDetailsService() {
//        return adminDetailService;
//    }
}